
import request from '../until/request.ts';

export interface Filters {
    title: string;
    imageURL: string;
    order: string;
    writer: string;
    introduction: string;
  }
  
  export interface NewsItem {
    id: number;
    title: string;
    writer: string;
    enterprise_name: string;
    content: string;
    introduction: string;
    imageURL: string;
  }
  interface BackResponse<T> {
    code: number;
    data: T;
    message: string;
  }

  export const getNewsList = async (): Promise<NewsItem[]> => {
    const response = await request.get<BackResponse<NewsItem[]>>('/news/list');
    if (response.data.code === 0) {
      return response.data.data; // 返回新闻列表数据
    } else {
      throw new Error(response.data.message || '获取新闻列表失败');
    }
  };

  export const editNew = async (news: NewsItem): Promise<void> => {
    const response = await request.post<BackResponse<void>>('/news/update', news);
    
    if (response.data.code !== 0) {
      throw new Error(response.data.message || '编辑新闻失败');
    }
  }

  export const exportFile = async (): Promise<void> => {
    try {
      const response = await request({
        url: '/export/news',
        method: 'GET',
        responseType: 'blob',  // 重要：确保响应类型为 'blob'
      });
  
      // 创建一个下载链接并模拟点击，从而实现文件下载
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'news.xlsx');  // 为下载的文件指定默认文件名
      document.body.appendChild(link);
      link.click();
  
      // 清理创建的URL和链接元素
      link.parentNode.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      throw new Error('导出失败');
    }
  };
  
  
  export const addNew = async (news: NewsItem): Promise<string> => {
    const response = await request.post<BackResponse<string>>('/news/add', news);
    if (response.data.code === 0) {
      return response.data.message; // 返回消息
    } else {
      throw new Error(response.data.message || '获取新闻列表失败');
    }
  }

  export const searchNews = async (news: Filters): Promise<NewsItem[]> => {
    const response = await request.post<BackResponse<NewsItem[]>>('/news/search', news);
    if (response.data.code === 0) {
      return response.data.data; // 返回新闻列表数据
    } else {
      throw new Error(response.data.message || '获取新闻列表失败');
    }
  }
  export const deleteNew = async(id: number): Promise<void>=> {
    const payload = { id: id };
    const response = await request.post<BackResponse<void>>('/news/delete', payload);
    if (response.data.code !== 0) {
      throw new Error(response.data.message || '删除新闻失败');
    }
  }